package com.puppet.bookstore_cache.service.impl;

import com.puppet.bookstore_cache.pojo.Book;
import com.puppet.bookstore_cache.service.BookService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {
    @Override
    //先从缓存中查找，如果找不到，再从数据库中查找，然后把结果存入缓存中
    @Cacheable(cacheNames = "books", key = "#id")
    public Book findById(Integer id) {
        // 假设这里从数据库中查询到了一本书
        Book book = new Book();
        book.setId(id);
        book.setName("Java编程思想");
        book.setAuthor("Bruce Eckel");
        System.out.println("访问数据库通过" + id + "查询一本书");
        return book;
    }

    @Override
    //先更新数据库，然后更新缓存
    @CachePut(cacheNames = "books", key = "#book.id")
    public Book update(Book book) {
        System.out.println("更新数据库：" + book);
        return book;
    }

    @Override
    //先删除数据库中的数据，然后删除缓存中的数据
    @CacheEvict(cacheNames = "books", key = "#id")
    public void delete(Integer id) {
        System.out.println("删除数据库中id为："+ id + "的书");
    }


    @Override
    //先删除数据库中的所有数据，然后删除缓存中这个名字下所有数据
    @CacheEvict(cacheNames = "books", allEntries = true)
    public void deleteAll() {
        System.out.println("删除数据库中所有的书籍");
    }
}
